#include <stdio.h>
#include <stdlib.h>
#include "syscall.h"

//Default Port Number
#define PORT 15

//Number of Ports that can be connected
#define MAXCONNECT 20

//Length of messages sent;
#define TEXTLENGTH 255

//File Descriptors
#define STDIN 0
#define STDOUT 1

//**GLOBAL VARIABLES**//
char buffer[TEXTLENGTH];
int sockets[MAXCONNECT];
int connected; //Number of connections
int sock;

void signal(char message, int length){
    for(int i=0; i<MAXCONNECT; i++){
        if(sockets[i]!=NULL){
                write(sockets[i],message, length);
        }
    }
}

/*
 * Looks to see if a socket is currently open. If not return the value -1 else
 * return a -1.
 * @return socket number
 */
int checkOpen(){
    for(int i=0; i<MAXCONNECT; i++){
        if(sockets[i]!=NULL)return i;
    }
    return -1; //No connections available
}

int submit(char message[TEXTLENGTH]){
    //Display it to our console!
    int bytesWritten;
    int socket;
    
    bytesWritten=write(socket,message,TEXTLENGTH);
    //Error Checking
    if(bytesWritten!=TEXTLENGTH) printf("Error: The entire string was not written.");
    if(bytesWritten==-1)printf("Error: Error with parameters, length of string, etc");
}

int main(int argc, char** argv){
    int bytesRead;
    int position;
    char buffer[TEXTLENGTH];
    
    for(int i=0; i<MAXCONNECT; i++){
        sockets[i]=NULL;
    }
    
    while(1==1){
        //Checks to see if a connection is open and then opens the port.
        sock=checkOpen();
        if(sock!=-1){
            sockets[sock]=accept(PORT);
            if(sockets[sock]==-1){//Unable or no connections
                sockets[sock]=NULL;
            }
        }
        for(int i=0; i<MAXCONNECT; i++){
            bytesRead=read(sockets[i],buffer,1);//See if something was read.
            if(-1!=bytesRead){
                while(1==1){
                        if(1!=read(sockets[i], buffer[++position],1))break;
                        if(buffer[position]=='\n'||position>=(TEXTLENGTH-1))break;
                }
                if(position>=(TEXTLENGTH-1))buffer[TEXTLENGTH]='\n';
                position=0;
                signal(buffer, bytesRead);
            }
        }
    }
    
    //Terminate for whatever reason, close all ports
    for(int i=0;i<MAXCONNECT;i++){
        if(close(sockets[i])==-1){
            printf("Unable to close connection for socket %d.", i);
        }
    }
}